﻿package igz.fleaxy.ui.text 
{
	import flash.text.AntiAliasType;
	import flash.text.StyleSheet;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import igz.fleaxy.Fleaxy;
	import igz.fleaxy.css.CssManager;
	import igz.fleaxy.util.ObjectUtil;
	import flash.text.Font;
	
	/**
	 * @author Intelygenz | www.intelygenz.com
	 */
	public class TextUi extends TextField {

		private var _Settings :Object;
		
		private const _STYLE_SUFIX:String = "</SPAN>";
		
		protected var _StyleName:String = "";
		
		/**
		* Es un TextField preparado para usar hojas de estilo de manera sencilla.
		* 
		* @param	p_htmlText Texto html
		* @param	p_style    Nombre de clase de la CSS
		* @param	p_settings { "cssName" : Fleaxy.$Current.$ConfigurationManager.$DefaultCssName }
		* 
		* @example
		* 
		* var texto:TextUi = new TextUi( "Texto"
		* 								, "classNameTexto"
		* 								, { "cssName": "myStyle.css"}
		* 							   );
		* addChild(texto);
		* 
		*/
		public function TextUi ( p_htmlText:String = "", p_style:String = "", p_settings:Object = null ) {
			super();

			var cssName:String = "";
			if ( Fleaxy.$Current != null && Fleaxy.$Current.$ConfigurationManager != null ) {
				cssName = Fleaxy.$Current.$ConfigurationManager.$DefaultCssName;
			}

			_Settings = {
				 "cssName" : cssName
			}
			ObjectUtil.$Merge( p_settings, _Settings );

			if ( p_style != "" ) {
				this.$StyleName = p_style;
			}
			else {
				_SetEmbedFonts( this.defaultTextFormat.font );
			}

			this.htmlText = p_htmlText;
			this.cacheAsBitmap = true;
		}

		private function _SetStyleSheet () : void {
			if ( this.type == TextFieldType.INPUT ) {
				this.styleSheet = null;
				if ( _StyleName != "" ) {
					var css:StyleSheet = Fleaxy.$Current.$CssManager.$GetStyleSheet( _Settings["cssName"] );
					this.defaultTextFormat = css.transform( css.getStyle("." + _StyleName) );
					this.setTextFormat( this.defaultTextFormat );
				}
			}
			else {
				this.styleSheet = Fleaxy.$Current.$CssManager.$GetStyleSheet( _Settings["cssName"] );
			}
		}

		private function get _StylePrefix():String {
			return "<SPAN class='" + _StyleName + "'>";
		}
		
		/*
		 * Fija diversos valores del TextField según el CSS asociado.
		 */
		private function _SetSettingsByCss () : void {
			// Antialias
			var igzStyle:String = Fleaxy.$Current.$CssManager.$GetStyleValue(_StyleName, CssManager.$STYLE_ANTIALIAS, _Settings["cssName"]);
			if ( igzStyle!=null ) {
				this.antiAliasType = igzStyle;
			}
				
			// Background
			igzStyle = Fleaxy.$Current.$CssManager.$GetStyleValue(_StyleName, CssManager.$STYLE_BACKGROUND, _Settings["cssName"]);
			if ( igzStyle != null ) {
				this.background = true;
				this.backgroundColor = uint( igzStyle );
			}
				
			// Border
			igzStyle = Fleaxy.$Current.$CssManager.$GetStyleValue(_StyleName, CssManager.$STYLE_BORDER, _Settings["cssName"]);
			if ( igzStyle != null ) {
				this.border = true;
				this.borderColor = uint( igzStyle );
			}
			
			// Alpha
			igzStyle = Fleaxy.$Current.$CssManager.$GetStyleValue(_StyleName, CssManager.$STYLE_ALPHA, _Settings["cssName"]);
			if ( igzStyle != null ) {
				this.alpha = Number( igzStyle );
			}
			
			// Filters
			this.filters = Fleaxy.$Current.$CssManager.$GetStyleFilters(_StyleName, _Settings["cssName"]);
		}

		private function _SetEmbedFonts(p_fontName:String):void {
			var found:Boolean = false;
			
			var fonts:Array = Font.enumerateFonts(); // Fuentes embebidas
			var font:Font;
			for each (font in fonts) {
				if ( font.fontName == p_fontName ) {
					embedFonts = true;
					found = true;
					break;
				}
			}
			if ( !found ) {
				fonts = Font.enumerateFonts(true); // Todas las fuentes
				for each ( font in fonts) {
					if ( font.fontName == p_fontName ) {
						embedFonts = false;
						found = true;
						break;
					}
				}
			}

			if ( !found ) {
				trace("igz.fleaxy.text.ui.TextUi -> La fuente especificada [" + p_fontName +"] en la clase ["+ _StyleName +"] no está embebida ni instalada en el sistema");
			}
		}
		
		public function get $StyleName() : String {
			return _StyleName;
		}

		public function set $StyleName( p_styleName:String ) : void {
			_StyleName = p_styleName.toLowerCase();

			_SetStyleSheet();
//trace("->"+this.htmlText+"_________"+this.text+"____"+styleSheet.styleNames.indexOf("."+p_styleName))
			_SetEmbedFonts( Fleaxy.$Current.$CssManager.$GetStyleValue(_StyleName, "fontFamily", _Settings["cssName"]) );
			_SetSettingsByCss();

			this.htmlText = this.htmlText;
		}
		
		override public function set type ( p_type : String ) : void {
			super.type = p_type;
			_SetStyleSheet();
		}

		override public function set htmlText(p_htmlText:String) : void {
			if ( (_StyleName != "") && (this.type != TextFieldType.INPUT)  ) {
				this.styleSheet = this.styleSheet;
				super.htmlText = this._StylePrefix + p_htmlText + this._STYLE_SUFIX;
			}
			else {
				this.styleSheet = null;
				this.defaultTextFormat = this.defaultTextFormat;
				super.htmlText = p_htmlText;
			}
			this.height = this.textHeight + 8; // TODO: Investigar porque calcula mal el alto del texto o buscar qué hay que sumar para ajustarlo correctamente
		}
		
		override public function get htmlText() : String {
			var htmlText:String = super.htmlText;
			
			if ( this.type != TextFieldType.INPUT ) {
				htmlText = htmlText.replace(this._StylePrefix, "");
				htmlText = htmlText.substring(0, htmlText.length - this._STYLE_SUFIX.length)
			}
			
			return htmlText;
		}

	}
	
}